import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class RemoveFromCartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String productId = request.getParameter("productId");

        if (productId == null || productId.isEmpty()) {
            response.sendRedirect("view-cart");
            return;
        }

        // 获取购物车Cookie
        Cookie cartCookie = getCartCookie(request);
        String cartJson = URLDecoder.decode(cartCookie.getValue(), "UTF-8");

        // 解析JSON购物车数据
        Gson gson = new Gson();
        Type cartType = new TypeToken<List<CartItem>>(){}.getType();
        List<CartItem> cartItems = gson.fromJson(cartJson, cartType);

        if (cartItems != null && !cartItems.isEmpty()) {
            // 移除指定商品
            cartItems.removeIf(item -> item.getProductId().equals(productId));

            // 将购物车数据转换为JSON
            String newCartJson = gson.toJson(cartItems);

            // 更新Cookie值（URL编码）
            cartCookie.setValue(URLEncoder.encode(newCartJson, "UTF-8"));
            cartCookie.setMaxAge(30 * 24 * 60 * 60); // 30天有效期
            cartCookie.setPath("/");
            response.addCookie(cartCookie);
        }

        // 重定向回购物车页面
        response.sendRedirect("view-cart");
    }

    private Cookie getCartCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("cart".equals(cookie.getName())) {
                    return cookie;
                }
            }
        }
        return new Cookie("cart", "[]");
    }
}